#include "canvas.h"
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QImageReader>
#include <QDate>
#include <QDesktopServices>
#include <QDirIterator>

Canvas::Canvas(QDeclarativeItem *parent) :
    QDeclarativeItem(parent),
    m_color(Qt::black),
    m_penX(0),
    m_penY(0),
    m_penWidth(1),
    m_capStyle(Qt::RoundCap),
    m_joinStyle(Qt::RoundJoin)
{
    setFlag(QGraphicsItem::ItemHasNoContents,false);
}

void Canvas::paint(QPainter* painter, const QStyleOptionGraphicsItem* styleOption, QWidget* widget)
{
    qDebug() << __PRETTY_FUNCTION__;    
    QPen pen(QBrush(m_color),m_penWidth,Qt::SolidLine,m_capStyle,m_joinStyle);
    if(smooth()){
        painter->setRenderHint(QPainter::Antialiasing,true);
    }

    m_penPoints.append( qMakePair(QPointF(m_penX,m_penY),pen) );
    for(int i=0;i<m_penPoints.count();i++){
        QPair<QPointF,QPen> pair = m_penPoints.at(i);
        painter->setPen(pair.second);
        painter->drawPoint(pair.first);
    }
}

void Canvas::undo()
{
    m_penPoints.takeLast();
    update();
}

void Canvas::save(QString filename)
{
    qDebug() << __PRETTY_FUNCTION__;    
    bool canContinue = false;

    if(QFile::exists(filename))
        canContinue = QFile::remove(filename);
    else
        canContinue = true;

    if(canContinue){
        QFile underFilename(m_underneathImageFilename.toLocalFile());
        QImage* underImage;
        bool saved = false;
        qDebug() << "under: " <<underFilename.fileName() << " url: " <<m_underneathImageFilename;
        if(underFilename.open(QIODevice::ReadOnly)){
            qDebug() << "file exists";

            QScopedPointer<QImageReader> reader(new QImageReader(&underFilename));
            underImage = new QImage(reader->read());
            qDebug() << "Error msg: " << reader->error();
            if(reader->error() || underImage->isNull()){
                qDebug() << "Error msg: " << reader->errorString();
            }
        }else{
            qDebug() << "file not found";
        }

        if(underImage!=NULL){
            QPainter* painter = new QPainter();
            painter->begin(underImage);
            for(int i=0;i<m_penPoints.count();i++){
                QPair<QPointF,QPen> pair = m_penPoints.at(i);
                qDebug() << "point: " << pair.first << " pen: " << pair.second;
                painter->setRenderHint(QPainter::Antialiasing,true);
                painter->setPen(pair.second);
                painter->drawPoint(pair.first);
            }
            painter->end();

            saved = underImage->save(filename);
            qDebug() << "saved: " << saved;
        }
        emit saveFinished(saved);
    }
}

QString Canvas::freeFilename()
{
    qDebug() << __PRETTY_FUNCTION__;
    QString fn;
    int count=0;
    int subcount = 0;
    QString date = QDate::currentDate().toString("ddMMyyyy");
    date = "paint"+date;

    QString path(QDesktopServices::storageLocation(QDesktopServices::PicturesLocation));
    path = path.split('/', QString::SkipEmptyParts).takeLast();
    path = "e:/"+path;
    QDirIterator di(path,QStringList() << "*.jpg",QDir::Files);
    while(di.hasNext()){
        QString name = di.next();
        QFileInfo fi(name);
        name = fi.baseName();
        if(QString::compare(date,name,Qt::CaseInsensitive)==0)
            count++;

        QStringList list = name.split('_');
        if(list.count()>1){
            if(QString::compare(date,list.at(0),Qt::CaseInsensitive)==0){
                if(subcount<list.at(1).toInt())
                    subcount = list.at(1).toInt();
            }
        }
    }

    if(subcount && !count)
        count = 1;
    count+=subcount;

    if(count)
        fn = date+"_"+QString::number(count)+".jpg";
    else
        fn = date+".jpg";

    fn = path+"/"+fn;
    qDebug() << "filename: " << fn;
    return fn;
}

QUrl Canvas::createEmpty(int width,int height)
{
    QUrl url;

    if(width>0 && height>0){
        QImage* img = new QImage(QSize(width,height),QImage::Format_RGB32);
        if(!img->isNull()){
            QPainter* painter = new QPainter(img);
            painter->fillRect(img->rect(),Qt::white);
            delete painter;
        }
        QString fn(QDir::currentPath()+"/emptycanvas.jpg");
        qDebug() << "fn: " <<  fn;

        if(QFile::exists(fn))
            if(QFile::remove(fn))
                qDebug() << "remove success";

        bool save = img->save(fn);
        qDebug() << "save: " <<save;
        if(save){
            url = QUrl::fromLocalFile(fn);
        }
        delete img;
        m_penPoints.clear();
    }
    return url;
}

void Canvas::clear()
{
    m_penPoints.clear();
}
